//
//  CXHTradPlusBannerAdapter.m
//  CXHAdSDK-TradPlus
//
//  Created by 陈坤 on 2023/9/19.
//

#import "CXHTradPlusBannerAdapter.h"
#import <TradPlusAds/TradPlusAdWaterfallItem.h>
#import <CXHAdSDK-Core/CXHAdSDK.h>
#import <CXHAdSDK-Core/CXHAdSDKBannerAdView.h>
#import <CXHAdSDK-Kit/CXHUtilsKit.h>

@interface CXHTradPlusBannerAdapter ()<CXHSDKBannerAdViewDelegate>

@property (nonatomic, strong) CXHAdSDKBannerAdView *bannerView;

@property (nonatomic, assign) BOOL isInit;

@property (nonatomic, assign) BOOL isC2SBidding;

@end

@implementation CXHTradPlusBannerAdapter

//根据event实现相关流程
- (BOOL)extraActWithEvent:(NSString *)event info:(NSDictionary *)config
{
    if([event isEqualToString:@"C2SBidding"]){
        //从三方SDK获取价格
        [self getECPMC2SBidding];
    } else if([event isEqualToString:@"LoadAdC2SBidding"]) {
//        [self.bannerView sendWinNotice:self.bannerView.getBidPrice];
        [self loadAdC2SBidding];
    } else if ([event isEqualToString:@"C2SLoss"]) {
        NSString *topPirce = config[@"topPirce_cny"];
        [self.bannerView sendLossNotice:[topPirce integerValue]];
    } else {
        return NO;
    }
    return YES;
}

- (void)loadAdC2SBidding {
    if ([self isReady]) {
        [self.bannerView sendWinNotice:self.bannerView.getBidPrice];
        [self AdLoadFinsh];
    }else{
        NSError *loadError = [NSError errorWithDomain:@"Load banner failed" code:-4 userInfo:@{NSLocalizedDescriptionKey : @"C2S banner not ready"}];
        [self AdLoadFailWithError:loadError];
    }
}

- (void)getECPMC2SBidding {
//    [self initSDK:self.waterfallItem.config];
    [self startC2SBidding];
}

//通过三方API获取ECPM
- (void)startC2SBidding {
    self.isC2SBidding = YES;
    NSString *posid = self.waterfallItem.config[@"posid"];
    
    if (kCXHStringIsEmpty(posid)) {
        NSDictionary *dic = @{@"error": @"get bid price failed"};
        [self ADLoadExtraCallbackWithEvent:@"C2SBiddingFail" info:dic];
        return;
    }
    
    self.bannerView.posId = posid;
    //竞价成功后的加载流程
    [self loadAdWithWaterfallItem:self.waterfallItem];
}

- (CXHAdSDKBannerAdView *)bannerView{
    if (_bannerView == nil) {
        _bannerView = [[CXHAdSDKBannerAdView alloc] initWithFrame:CGRectMake(0, 0, self.waterfallItem.bannerSize.width, self.waterfallItem.bannerSize.height)];
        _bannerView.delegate = self;
    }
    return _bannerView;
}

- (void)loadAdWithWaterfallItem:(TradPlusAdWaterfallItem *)item{
    [self initSDK:item.config];
    //通过 item.config 获取后台配置信息
    NSString *posid = item.config[@"posid"];
    
    if (kCXHStringIsEmpty(posid)) {
        [self AdConfigError];
        return;
    }

    self.bannerView.controller = item.bannerRootViewController;
    self.bannerView.posId = posid;
    
    [self.bannerView loadAndShow];
}

- (void)initSDK:(NSDictionary *)config {
    if (self.isInit) {
        return;
    }
    self.isInit = YES;
    NSString *domain = [config CXH_objectOrNilForKey:@"domain"];
    if (kCXHStringIsEmpty(domain)) {
        domain = @"";
    }
    
    NSString *appid = [config CXH_objectOrNilForKey:@"appid"];
    if (!kCXHStringIsEmpty(appid)) {
        [CXHAdSDK initWithAppId:appid requestDomain:domain  completionBlock:^(NSError * _Nullable error) {
            if (error) {
                [self AdConfigError];
            }
        }];
    }
}

//此方法用于返回是否过期状态
- (BOOL)isReady{
    return (self.bannerView != nil);
}

//返回加载完成后的横幅对象
- (id)getCustomObject{
    return self.bannerView;
}

//- (void)bannerDidAddSubView:(UIView *)subView{
//    if(subView.bounds.size.width != 0){
//        CGRect rect = self.bannerView.frame;
//        rect.size.width = subView.bounds.size.width;
//        self.bannerView.frame = rect;
//    }
//}

#pragma mark - CXHSDKBannerAdViewDelegate
/**
 广告获取成功
 
 @param bannerView banner实例
 */
- (void)CXH_bannerViewDidReceived:(CXHAdSDKBannerAdView *)bannerView{
    if (self.isC2SBidding) {
        NSInteger price = self.bannerView.getBidPrice;
        if (price <= 0) {
            NSDictionary *dic = @{@"error": @"get bid price failed"};
            [self ADLoadExtraCallbackWithEvent:@"C2SBiddingFail" info:dic];
            return;
        }
        //通过接口向TradPlusSDK回传ecpm和三方版本号
        float f = price/100.00;
        NSString *ecpmStr = [NSString stringWithFormat:@"%.2f", f];
        NSDictionary *dic = @{@"ecpm":ecpmStr,@"version":[CXHAdSDK getSDKVersion]};
        [self ADLoadExtraCallbackWithEvent:@"C2SBiddingFinish" info:dic];
    } else {
        [self AdLoadFinsh];
    }
}

/**
 广告拉取失败
 
 @param bannerView banner实例
 @param error 错误描述
 */
- (void)CXH_bannerViewFailToReceived:(CXHAdSDKBannerAdView *)bannerView error:(NSError *)error{
    [self AdLoadFailWithError:error];
}

/**
 广告点击
 
 @param bannerView 广告实例
 @param loadingPageURL 广告落地页地址，当渠道为bwt，并且customLoadingPage为YES时有值
 */
- (void)CXH_bannerViewClicked:(CXHAdSDKBannerAdView *)bannerView loadingPageURL:(NSString *)loadingPageURL{
    [self AdClick];
}

/**
 广告关闭
 
 @param bannerView 广告实例
 */
- (void)CXH_bannerViewClose:(CXHAdSDKBannerAdView *)bannerView{
    [self AdClose];
}

/**
 广告展示
 
 @param bannerView 广告实例
 */
- (void)CXH_bannerViewExposure:(CXHAdSDKBannerAdView *)bannerView{
    [self AdShow];
}

/**
 关闭落地页
 
 @param bannerView 广告实例
 */
- (void)CXH_bannerAdCloseLandingPage:(CXHAdSDKBannerAdView *)bannerView{
}

@end
